package com.home.customtest.typehandle;

import com.custom.jdbc.handler.AbstractTypeHandler;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author XiaoBai
 * @since 2024/4/12 14:48
 */
public class CustomStringTypeHandler extends AbstractTypeHandler<String> {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT);
    @Override
    public String getTypeValue(Object val) {
        if (val instanceof Date) {
            return SIMPLE_DATE_FORMAT.format(val);
        }
        return null;
    }

    @Override
    public String getTypeValue(ResultSet rs, int index) throws SQLException {
        return getTypeValue(rs.getString(index));
    }

    @Override
    public void setTypeValue(PreparedStatement statement, int index, String val) throws Exception {
        statement.setTimestamp(index, new java.sql.Timestamp(SIMPLE_DATE_FORMAT.parse(val).getTime()));
    }
}
